#include "FileBuffer.h"

FileBuffer::FileBuffer()
:m_buffer(NULL),
 m_buffer_size(0),
 m_is_malloc(false)
{
}

int FileBuffer::buffer_new(int size)
{
	if(NULL == m_buffer && false == m_is_malloc) {
		m_buffer = (void*)new char[size];
		m_buffer_size = size;
		m_is_malloc = true;
		memset(m_buffer, 0, m_buffer_size);
		return size;
	}
	else if(true == m_is_malloc){
#ifdef DEBUG_BUFFER
		cout<<"FileBuffer::buffer_new: buffer has been malloced."<<endl;
#endif
		memset(m_buffer, 0, m_buffer_size);
		return m_buffer_size;
	}
	else {
#ifdef DEBUG_BUFFER
		cout<<"FileBuffer::buffer_new: set m_buffer to NULL before malloc"<<endl;
#endif
		buffer_free();
		m_buffer = (void*)new char[size];
		m_buffer_size = size;
		m_is_malloc = true;
		memset(m_buffer, 0, m_buffer_size);
		return size;
	}
}

void FileBuffer::buffer_free()
{
	if(true == m_is_malloc && NULL != m_buffer) {
		delete [] m_buffer;
		m_buffer = NULL;
		m_is_malloc = false;
		m_buffer_size = 0;
	}
	else if(false == m_is_malloc && NULL != m_buffer) {
		cout<<"FileBuffer::buffer_free: set m_buffer to NULL "
				"because buffer has not been malloced"<<endl;
		m_buffer = NULL;
		m_buffer_size = 0;
	}
	else if(true == m_is_malloc && NULL == m_buffer) {
		cout<<"FileBuffer::buffer_free: Error occured: "
				"m_bufferis equal to NULL, but malloc flag"
				"is true."<<endl;
		m_is_malloc = false;
		m_buffer_size = 0;
	}
	else {
		cout<<"FileBuffer::buffer_free: "
				"Buffer has already been freed."<<endl;
	}
}

void* FileBuffer::buffer_get()
{
	return m_buffer;
}

size_t FileBuffer::buffer_get_size()
{
	return m_buffer_size;
}
